﻿using System;
using System.ComponentModel;
using System.Windows;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Controls;

namespace VisualWip.TFS2010Providers
{
    /// <summary>
    /// Interaction logic for WorkItemEditor.xaml
    /// </summary>
    public partial class WorkItemEditor
    {
        private readonly WorkItemFormControl _workItemFormControl;

        public WorkItemEditor()
        {
            InitializeComponent();

            _workItemFormControl = new WorkItemFormControl();

            WorkItemControlHost.Child = _workItemFormControl;
        }


        public void SetWorkItem(WorkItem workItem)
        {
            _workItemFormControl.Item = workItem;
            Title = string.Format("{0}: {1} {2}", workItem.Type.Name, workItem.Id, workItem.Title);
        }

        private void SaveButtonClick(object sender, RoutedEventArgs e)
        {
            if (!_workItemFormControl.Item.IsDirty)
                return;

            SaveWorkItem();
        }

        private void SaveWorkItem()
        {
            try
            {
                _workItemFormControl.Item.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error saving work item", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void RefreshClick(object sender, RoutedEventArgs e)
        {
            try
            {
                _workItemFormControl.Item.SyncToLatest();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error refreshing work item", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ResetClick(object sender, RoutedEventArgs e)
        {
            _workItemFormControl.Item.Reset();
        }

        private void RibbonWindowClosing(object sender, CancelEventArgs e)
        {
            if (_workItemFormControl.Item.IsDirty)
            {
                MessageBoxResult dialogResult = MessageBox.Show("Do you want to save the work item?", "Save work item",
                                                                MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                if (dialogResult == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }

                if (dialogResult == MessageBoxResult.Yes)
                    SaveWorkItem();
            }
        }
    }
}